
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/resource.h>

#include <librally.h>

Err rp_daemonize(int nochdir, int noclose)
{
	char fname[] = "rp_daemonize";
	char msg[] = "fatal error";
	Err err;
	int fd;
	FLOG_IN(fname);
	
	pid_t pid = fork();
    	switch (pid) 
	{
    		case (-1) : {
			//rp_log(LOG_FATAL, fname, "Failed to create new process: %s", strerror(errno));
			return E_FATAL;
		}
		case (0) : {
			break;
		}
		default : {
			int i = 0;
			exit(0);
		}
    	}
		
    	if (setsid() == -1)
       { 
       	//rp_log(LOG_FATAL, fname, "Failed to set new session id: %s", strerror(errno));
       	return err;
    	}

	/*	Set the coredump to the hard limit     */
       struct rlimit rlim;
       if (getrlimit(RLIMIT_CORE, &rlim) != -1) 
	{
       	rlim.rlim_cur = rlim.rlim_max;
              setrlimit(RLIMIT_CORE, &rlim);
	}
	/* Set the nofile to the hard limit */    
       if (getrlimit(RLIMIT_NOFILE, &rlim) != -1) 
	{
       	rlim.rlim_cur = rlim.rlim_max;
              setrlimit(RLIMIT_NOFILE, &rlim);
	}

	int i;
	for (i = 0 ; i < 3 ; i++) close(i);	
    	if (!nochdir) (void)chdir("/");
    	if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) 
	{
       	(void)dup2(fd, STDIN_FILENO);
       	(void)dup2(fd, STDOUT_FILENO);
       	(void)dup2(fd, STDERR_FILENO);
       	if (fd > STDERR_FILENO) (void)close(fd);
	}

	FLOG_OUT(fname);
	return E_OK;
}

